#!/usr/bin/env python3

class Menu:
    def __init__(self, **kargs):
        """
        菜单对象初始化
        """
        self.level = 0
        self.items = []
        self.title = '菜单标题'
        self.quitStr = '退出'
        self.__dict__.update(kargs)

    def add(self, msg, handle=None):
        """
        给菜单添加项
            handle == None      添加退出项
            handle == callable  添加菜单项
            handle == Menu      添加子菜单
        """
        item = {}
        item['msg'] = msg
        item['handle'] = handle
        if isinstance(handle, Menu):
            handle.level = self.level + 1
        self.items.append(item)

        return self

    def showItems(self):
        for index, it in enumerate(self.items):
            print("%s%d. %s" % ('    ' * self.level, index + 1, it['msg']))

    def getInput(self, num):
        while True:
            s = input("%s请输入[1 - %d]: " % ('    ' * self.level, num))
            if not s:
                continue
            n = int(s)
            if 1 <= n <= num:
                return n

    def addQuitItem(self):
        """
        添加退出菜单项
        """
        addFlags = True
        for x in self.items:
            if None in x.values():
                addFlags = False
                break

        if addFlags:
            quitStr = self.quitStr if self.level == 0 else "返回上一级"
            self.add(quitStr)

    def run(self):
        """
        运行菜单程序
        """

        self.addQuitItem()

        itemNum = len(self.items)

        #  循环菜单执行
        while True:
            #  打印菜单标题
            print("%s%s" % ('    ' * self.level, self.title))
            #  输出菜单项
            self.showItems()

            #  获取用户输入
            i = self.getInput(itemNum)

            #  根据用户输入执行菜单项
            handle = self.items[i - 1]['handle']
            if not handle:
                break
            elif isinstance(handle, Menu):
                handle.run()
            else:
                handle(i)

if __name__ == "__main__":
    def t(index):
        if index == 1:
            print("三角形主处理函数")
        elif index == 2:
            print("右上三角形处理函数")
        elif index == 3:
            print("左上三角形处理函数")
        elif index == 4:
            print("右下三角形处理函数")

    def g(index):
        if index == 2:
            print("正方形处理函数")
        elif index == 3:
            print("棱形处理函数")

    m = Menu()
    ms = Menu(title='三角形子菜单')
    mss = Menu(title='三角形三角形子菜单')

    m.add("三角形", ms).add("正方形", g).add("棱形", g)

    ms.add("三角形1", t)
    ms.add("三角形2", t)
    ms.add("三角形3", t)
    ms.add("三角形4", t)
    ms.add('三角形子菜单子菜单', mss)

    mss.add("三角形A", t)
    mss.add("三角形B", t)
    mss.add("三角形C", t)
    mss.add("三角形D", t)

    m.run()

